<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  batchList(v-model="batchListShow" :batchNumber="batchNumber"  @message-to-parent="request('tableData')")
  templatePreview(v-model="templateShow" :selectRows="selectRow")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type IAction,
  type DataPageProps,
  type TableProps,
  Icon,
} from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import type {
  InspectionAgencyEntity,
  InspectionAgencyQueryParams,
} from "@scmt/api-lis-inspection-agency";
import batchList from "./compoments/batchList.vue";
import templatePreview from "../inspection/compoments/templatePreview.vue";

const $api = useApi();
const queryPramas = reactive<InspectionAgencyQueryParams>({
  signingStartDate: "",
  signingEndDate: "",
  get _tempDate() {
    return [this.signingStartDate, this.signingEndDate];
  },
  set _tempDate(val) {
    [this.signingStartDate, this.signingEndDate] = val || ["", ""];
  },
  pageNum: 1,
  pageSize: 20,
});

const templateShow = ref(false);
const selectRow = ref({});
const batchNumber = ref("");

const batchListShow = computed({
  get() {
    return Boolean(batchNumber.value);
  },
  set(val) {
    !val && (batchNumber.value = "");
  },
});

const { request, data, loadingMap } = useRequest({
  tableData: (q: any) => {
    const { _tempDate, ...params } = Object.assign({}, queryPramas, q);
    return $api.lis.inspectionAgency.query(params);
  },
  listDoctorAsOptions: (val: string) =>
    $api.user.listDoctorAsOptions({ officeId: val }),
});

onMounted(() => {
  request("tableData");
  request("listDoctorAsOptions");
});

const pageParams = computed<DataPageProps>(() => {
  const queryFields: FormItemProps[] = [
    // {
    //   prop: "state",
    //   label: "批次状态",
    //   as: "select",
    //   options: {
    //     loadMethod: () => {
    //       return [
    //         {
    //           label: "已送检",
    //           value: 1,
    //         },
    //         {
    //           label: "已签收",
    //           value: 2,
    //         },
    //       ];
    //     },
    //   },
    // },
    {
      prop: "batchNumber",
      label: "批次号",
    },
    {
      prop: "_tempDate",
      label: "签收时间",
      as: "date",
      options: {
        type: "daterange",
      },
      span: 6,
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields,
    onQuery: () => request("tableData"),
    onAct: onPageActions,
    alignAction: "right",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        prop: "batchNumber",
        label: "批次号",
        width: 170,
      },
      {
        prop: "state",
        label: "批次状态",
        sortable: true,
        tooltip: true,
        render: ({ row }) => {
          let iconName = "";
          let content = "";
          let color = "";
          switch (row.state) {
            case 1: {
              iconName = "Promotion";
              content = "待签收";
              color = "green";
              break;
            }
            case 2: {
              iconName = "Memo";
              content = "已签收";
              color = "orange";
              break;
            }
          }
          return h(
            "div",
            {
              style: {
                display: "flex",
                alignItems: "center",
              },
            },
            [
              h(Icon, {
                name: iconName,
                style: {
                  color: color,
                },
              }),
              h(
                "span",
                {
                  style: {
                    marginLeft: "var(--mt-margin-small)",
                  },
                },
                content
              ),
            ]
          );
        },
      },
      {
        prop: "source",
        label: "业务来源",
        tooltip: true,
        sortable: true,
      },
      {
        prop: "specimenType",
        label: "标本类型",
        tooltip: true,
      },
      {
        prop: "numberPeople",
        label: "样本总数量",
        width: 300,
        render: ({
          row: { signNumber, signedNumber, rejectionNumber, numberPeople },
        }: {
          row: InspectionAgencyEntity;
        }) => {
          let str = "";

          if (signedNumber) {
            str += `(已签收：${signedNumber}`;
          }

          if (rejectionNumber) {
            str += `${str === "" ? "(" : ","}已拒收：${rejectionNumber}`;
          }

          if (signNumber) {
            str += `${str === "" ? "(" : ","}待签收：${signNumber}`;
          }

          return `合计：${numberPeople}${str ? str + ")" : ""}`;
        },
      },
      {
        prop: "sendInspectionId",
        label: "送检人",
        tooltip: true,
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.sendInspectionId;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter(
              (item) => item.value == row.sendInspectionId
            );
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "generationTime",
        label: "送检时间",
        format: "datetime",
      },
      {
        prop: "signee",
        label: "签收人",
        tooltip: true,
        render: ({ row }) => {
          const patientType = data.listDoctorAsOptions ?? [];
          let resText = row.signee;
          if (patientType && patientType.length > 0) {
            let filter = patientType.filter((item) => item.value == row.signee);
            if (filter && filter.length > 0) {
              resText = filter[0].label;
            }
          }
          return h("div", resText);
        },
      },
      {
        prop: "signingTime",
        label: "签收时间",
        sortable: true,
        format: "datetime",
      },
      {
        prop: "outward",
        label: "是否外送",
        tooltip: true,
        sortable: true,
        width: 130,
        render: ({ row }) => {
          if (row.outward == 1) {
            return h("div", "是");
          } else {
            return h("div", "否");
          }
        },
      },
      {
        label: "操作",
        fixed: "right",
        width: 220,
        actions: ({ row }) => {
          return [
            {
              label: "批量签收",
              event: "sign",
              type: "success",
              visible: row.state == 1,
            },
            {
              label: "签收明细",
              event: "detailed",
              type: "danger",
              visible: row.state == 2,
            },
            // {
            //   label: "打印送检单",
            //   event: "print",
            //   type: "primary",
            // },
          ].filter((i) => i.visible === void 0 || i.visible);
        },
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    highlightCurrentRow: true,
  };
  return tableProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "sign":
    case "detailed":
      batchNumber.value = model.batchNumber;
      break;
    case "print":
      templateShow.value = true;
      selectRow.value = $api.lis.inspectionAgency.$$createEntity(model);
      break;
  }
};
</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
